// 模块导入
import database from '../../utils/database'
import goodsService from './goods.service';
import shopService, {ShopGoodsItem} from './shop.service';
// 数据库中订单的表名
const orderTableName = 'Orders'

// 购物车服务类
export class OrdersService {
    // 创建订单
    create(address: string, uid: number) {
        return new Promise((resolve, reject)=>{
            // 获取当前购物车数据
            shopService.getShopCar(uid).then((shopCar: any)=>{
                // 对是否可下单进行校验
                let canCreate = true
                // 如果购物车中商品为空，不能下单
                if (shopCar.goods.length == 0) {
                    reject("购物车为空~")
                    return
                }
                // 检查购物车中所有商品的库存情况，有商品库存不足则不允许下单
                shopCar.goods.forEach((goods: any) => {
                    if (goods.item.stock < goods.count) {
                        canCreate = false
                    }
                });
                // 校验不通过，则提醒用户库存不足
                if (!canCreate) {
                    reject("有商品库存不足，请修改后下单~")
                } else {
                    // 更新修改商品库存与计算订单价格
                    let price = 0 // 订单实际总价
                    let save_price = 0 // 订单优惠价
                    let oriPrice = 0 // 订单原始总价
                    // 订单商品列表
                    let goodsJSON:ShopGoodsItem[] = []
                    // 进行价格计算
                    shopCar.goods.forEach((goods: any) => {
                        let item = goods.item
                        item.stock = item.stock - goods.count
                        item.category_id = item.category.id
                        goodsService.updateGoods(item)
                        goodsJSON.push({
                            gid: item.id,
                            count: goods.count
                        })
                        price += item.discounted_price * goods.count
                        oriPrice += item.price * goods.count
                    });
                    save_price = oriPrice - price
                    let goodsJSONString = JSON.stringify(goodsJSON)
                    // 调用数据库接口进行订单创建
                    database.insertData(orderTableName, ["user_id", "goods", "address", "price", "save_price", "state"], [uid, goodsJSONString, address, price, save_price, 0], (res)=>{
                        if (res == null) {
                            reject("订单创建失败")
                        } else {
                            // 创建成功后清空购物车
                            shopService.updateShopCar(uid, [])
                            resolve(null)
                        }
                    })
                }
            }).catch(()=>{
                reject("订单创建失败")
            })
        })
    }

    // 更新订单状态
    update(oid: number, state:number) {
        // 更新状态
        return new Promise((resolve)=>{
            database.updateData(orderTableName, `state=${state}`, `id=${oid}`)
            resolve(null)
        })
    }

    // 查询订单
    // 其中不传uid参数则为查询所有用户的订单
    query(offset: number, limit: number, uid?: number, order?: string, filter?: number) {
        return new Promise((resolve, reject)=>{
            // 拼接查询语句
            let where = ""
            // 存在用户id，则表名要查询某个具体用户的订单
            if (uid) { where += `user_id=${uid}`}
            // 拼接筛选条件
            if (filter || filter == 0) {
                if (where.length > 0) {
                    where += ` AND state=${filter}`
                } else {
                    where += `state=${filter}`
                }
            }
            if (where.length == 0) { where = `id IS NOT NULL` }
            // 拼接排序规则
            if (order) { where += ` ORDER BY ${order}` }
            // 拼接分页字段
            where += ` LIMIT ${limit} OFFSET ${offset}`
            // 查询订单数据
            database.queryData(orderTableName, ["*"], where, (data)=>{
                if (data) {
                    if (data.result.length == 0) {
                        resolve(null)
                    }
                    // 记录当前遍历的订单个数
                    let orderCount = 0
                    data.result.forEach((order:any) => {
                        // 查询商品数据后拼入订单对象中
                        let resultItems:any[] = []
                        let goodsItems = JSON.parse(order.goods ?? "")
                        // 跳过商品列表为空的异常场景
                        if (goodsItems.length == 0) {
                            orderCount += 1
                            order.goods = []
                            if (orderCount == data.result.length) {
                                resolve(data.result)
                            }
                            return
                        }
                        // 记录商品查询次数
                        let execTimes = 0
                        goodsItems.forEach((element: ShopGoodsItem) => {
                            // 查询商品详情
                            goodsService.getGoodsDetail(element.gid).then((goodsResult: any)=>{
                                // 存储商品数据
                                resultItems.push({
                                    count: element.count,
                                    item: goodsResult[0]
                                })
                                execTimes += 1
                                if (execTimes == goodsItems.length) {
                                    order.goods = resultItems
                                    orderCount += 1
                                    // 当所有订单都遍历过后，返回数据
                                    if (orderCount == data.result.length) {
                                        resolve(data.result)
                                    }
                                }
                            })
                        });
                   });
                } else {
                    reject('获取失败，请稍后重试')
                }
            })
        })
    }
}
// 导出服务实例
export default new OrdersService();